<?php

namespace app\home\controller;

use app\common\controller\Oauth;
use external\SFTools;

class Api extends Oauth {

    public function initialize() {
        //parent::initialize();
    }

    public function forward() {
        if (!request()->isPost()) {
            return SFTools::pullJson(0, '3301');
        }
        $data = input('post.');
        if (empty($data["url"])) {
            return SFTools::pullJson(0, '3110');
        }
        $index = strpos($data["url"],"/service/Oauth/");
        if($index != 0){
            return SFTools::pullJson(0, '3002');
        }
        $url = SERVICE_HTTP_X . SERVICE_BIND_HOST . $data["url"] . "?";
        unset($data["url"]);
        $cache_name = "forward_".SERVICE_APP_ID;
        $appFind = SFTools::getCache($cache_name);
        if (empty($appFind)) {
            $param = array(
                "appid" => SERVICE_APP_ID, "secret" => SERVICE_APP_SECRET
            );
            list($bool2, $returnJsonStr) = SFTools::http(SERVICE_HTTP_X . SERVICE_BIND_HOST . "/service/Authorize/getAccessToken?", $param);
            if($bool2 === false){
                return SFTools::pullJson(-1, "3111");
                //throw new \think\Exception($return_str);
            }
            $returnArray = SFTools::jsonDecode($returnJsonStr);
            SFTools::setCache($cache_name, $returnArray['data'], 7200);
            $appFind = $returnArray['data'];
        }
        $param = array(
            "appid" => SERVICE_APP_ID, "access_token" => $appFind["access_token"]
        );
        list($bool, $return_str) = SFTools::http($url, $param, $data, "POST");
        if($bool === false){
            return SFTools::pullJson(-1, "3001");
        }
        return json(SFTools::jsonDecode($return_str));
    }

}
